import { Entity, Column, ManyToOne, JoinColumn, Index } from 'typeorm';
import { BaseEntity } from '@app/common/entities/base.entity';
import { User } from './user.entity';

@Entity('announcements')
@Index(['type'])
@Index(['status'])
@Index(['publishedAt'])
@Index(['priority'])
export class Announcement extends BaseEntity {
  @Column({ type: 'varchar', length: 255 })
  title: string;

  @Column({ type: 'text' })
  content: string;

  @Column({ 
    type: 'enum', 
    enum: ['系统', '活动', '通知'], 
    default: '通知' 
  })
  type: '系统' | '活动' | '通知';

  @Column({ type: 'tinyint', default: 2, comment: '优先级: 1=低, 2=中, 3=高' })
  priority: number;

  @Column({ type: 'tinyint', default: 1, comment: '状态: 0=禁用, 1=启用' })
  status: number;

  @Column({ type: 'boolean', default: false })
  isTop: boolean;

  @Column({ type: 'timestamp'})
  publishedAt?: Date;

  @Column({ type: 'timestamp', nullable: true })
  expiredAt?: Date;

  @Column({ type: 'int', default: 0 })
  viewCount: number;

  @Column({ type: 'int', nullable: true })
  authorId?: number;

  @Column({ type: 'varchar', length: 100, nullable: true })
  authorName?: string;

  // 其他字段
  @Column({ type: 'varchar', length: 500, nullable: true })
  cover?: string;

  @Column({ type: 'text', nullable: true })
  summary?: string;

  @Column({ type: 'json', nullable: true })
  tags?: string[];

  @Column({ type: 'boolean', default: true })
  allowComment: boolean;

  @Column({ type: 'varchar', length: 7, default: '#1890ff' })
  color: string;

  // 作者关联
  @ManyToOne(() => User, { eager: false })
  @JoinColumn({ name: 'authorId' })
  author?: User;

  // 虚拟属性：是否已发布
  get isPublished(): boolean {
    return this.status === 1 && !!this.publishedAt && this.publishedAt <= new Date();
  }

  // 虚拟属性：是否已过期
  get isExpired(): boolean {
    return !!this.expiredAt && this.expiredAt < new Date();
  }

  // 虚拟属性：优先级文本
  get priorityText(): string {
    const map = { 1: '低', 2: '中', 3: '高' };
    return map[this.priority] || '中';
  }

  // 虚拟属性：类型图标
  get typeIcon(): string {
    const iconMap = {
      '系统': 'system',
      '活动': 'activity',
      '通知': 'notification'
    };
    return iconMap[this.type] || 'notification';
  }

  // 虚拟属性：状态文本
  get statusText(): string {
    if (this.isExpired) return '已过期';
    if (!this.isPublished) return '未发布';
    return '已发布';
  }

  // 虚拟属性：获取预览内容
  get preview(): string {
    if (this.summary) return this.summary;
    return this.content.replace(/<[^>]*>/g, '').slice(0, 100) + '...';
  }
}
